﻿using Elsa.Workflows.Management.Entities;
using Elsa.Workflows.Runtime.Messages;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using T.FAS.Runtime.MF.Activities;
using T.FAS.Runtime.MF.Entity;
using T.FAS.Runtime.MF.Service;
using T.FAS.Runtime.MF.SGSPI;
using T.ServiceComponent.Kernel.Service;

namespace T.FAS.Runtime.MF.SGPlugin
{
    [SGService]
    public class EngineService : IEngineService
    {
        [SGService(ServiceID = "FASMF-ExecuteWorkflow")]
        public SGResult<ElsaExecutionResult> ExecuteWorkflow(WorkflowExecuteParam param)
        {
            var service = new EngineExecuteService();
            try
            {
                var executeResult = service.ExecuteWorkflow(param.ID, param.Input);
                if (executeResult.Status == "Faulted")
                {

                   return  SGResult<ElsaExecutionResult>.Fail("0", null, string.Join(",", executeResult.WorkflowState.Incidents.Select(t => t.Exception.Message)));
                }
                return SGResult<ElsaExecutionResult>.Success(executeResult);
            }
            catch (Exception ex)
            {
                return SGResult<ElsaExecutionResult>.Fail("0", ex, $"工作流执行失败,{ex.ToString()}");
            }
           
        }

      

        public SGResult<List<WorkflowDefinition>> PublishWorkflow(string defJson)
        {
            var service = new EngineExecuteService();
            var resultData = new List<WorkflowDefinition>();

            try
            {
                // 反序列化JSON
                var workflowDefs = JsonConvert.DeserializeObject<List<Microflow>>(defJson, new ShapeConverter());
                var toPublishWorkflowDefs = new List<Microflow>();

                if (workflowDefs != null)
                {
                    foreach (Microflow microflow in workflowDefs)
                    {
                        if (microflow.DesignData == null || microflow.DesignData.Cells == null) continue;
                        microflow.DesignData.Cells.ForEach(cell => { cell.BelongTo = microflow; });
                        toPublishWorkflowDefs.Add(microflow);
                    }
                    resultData.AddRange(service.PublishWorkflow(toPublishWorkflowDefs));
                }

                return SGResult<List<WorkflowDefinition>>.Success(resultData);
            }
            catch (Exception ex)
            {
                return SGResult<List<WorkflowDefinition>>.Fail("0", ex, $"发布工作流失败,ex{ex.ToString()}");
            }
        }

        public SGResult<RunWorkflowInstanceResponse> StartWorkflow(WorkflowExecuteParam param)
        {
            try
            {
                var service = new EngineExecuteService();
                var startResult = service.StartWorkflow(param.ID, param.Input);
                return SGResult<RunWorkflowInstanceResponse>.Success(startResult);
            }
            catch (Exception ex)
            {
                return SGResult<RunWorkflowInstanceResponse>.Fail("0", ex, "启动工作流失败");
            }
           
        }

        public SGResult<List<WorkflowInstanceDetail>> GetExecuteDetail(string instanceId)
        {
            try
            {
                var service = new EngineExecuteService();
                var detailList = service.GetExecuteDetail(instanceId);
                return SGResult<List<WorkflowInstanceDetail>>.Success(detailList);
            }
            catch (Exception ex)
            {
                return SGResult<List<WorkflowInstanceDetail>>.Fail("0", ex, "获取工作流执行详情失败");
            }
        }

        public SGResult<ElsaExecutionResult> DebugWorkflow(WorkflowDebugParam param)
        {
            var service = new EngineExecuteService();
            try
            {
                var extraParams = new Dictionary<string, string>();
                extraParams.Add("DebugEnvUrl", param.DebugEnvUrl);
                extraParams.Add("AppID",param.AppID);
                var executeResult = service.ExecuteWorkflow(param.ID, param.Input, extraParams);
                if (executeResult.Status == "Faulted")
                {

                    return SGResult<ElsaExecutionResult>.Fail("0", null, string.Join(",", executeResult.WorkflowState.Incidents.Select(t => t.Exception.Message)));
                }
                return SGResult<ElsaExecutionResult>.Success(executeResult);
            }
            catch (Exception ex)
            {
                return SGResult<ElsaExecutionResult>.Fail("0", ex, $"工作流执行失败,{ex.ToString()}");
            }

        }
    }
}
